package top.xzxsrq.fileviewutils.service.impl;

import cn.hutool.core.io.FileUtil;
import lrc2video.zlm.tool.lv.main.Lrc2videoApp;
import lrc2video.zlm.tool.lv.util.DataUtil;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
import top.xzxsrq.fileviewutils.service.LrcService;
import top.xzxsrq.utils.PathUtils;
import top.xzxsrq.utils.StringUtilsZX;
import top.xzxsrq.web.utils.AjaxResult;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
public class LrcServiceImpl implements LrcService, CommandLineRunner, DisposableBean {
    // 开启线程池
    public static final ExecutorService executorService = Executors.newSingleThreadExecutor();

    static {
        DataUtil.init();
    }

    int viewWidth = 1920 / 2;// 图片宽度
    int viewHeight = 1080 / 2;// 图片
    int paddingHeight = 10;// 歌词间隔
    int fontSize = 60; // 字体大小

    @Autowired
    private FileServiceImpl fileService;

    @Override
    public AjaxResult run(List<String> paths) {
        String baseFilePathByUserId = fileService.getBaseFilePathByUserId();
        for (String path : paths) {
            String abPath = PathUtils.pathResolve(baseFilePathByUserId, path);
            boolean exist = FileUtil.exist(abPath);
            if (exist) {
                boolean directory = FileUtil.isDirectory(abPath);
                if (directory) {
                    executorService.submit(() -> {
                        try {
                            Lrc2videoApp.runDirFile(viewWidth, viewHeight, paddingHeight, fontSize, abPath);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    });
                } else {
                    String s = FileUtil.extName(abPath);
                    if (StringUtilsZX.isBlank(s)) {
                        continue;
                    }
                    if ("lrc".equals(s.toLowerCase())) {
                        executorService.submit(() -> {
                            try {
                                Lrc2videoApp.runSingFile(viewWidth, viewHeight, paddingHeight, fontSize, abPath);
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        });
                    }
                }
            }
        }
        return AjaxResult.success("提交完成");
    }

    @Override
    public void destroy() throws Exception {
        executorService.shutdownNow();
        Lrc2videoApp.executorService.shutdownNow();
    }

    @Override
    public void run(String... args) throws Exception {

    }
}
